<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace hiduoke\services;

use hiduoke\services\workWechat\WorkWechatOauth;
use think\Exception;
use app\common\model\system\Config;
use app\common\model\platform\Platform;
use hiduoke\services\workWechat\WorkWechatKfService;
use hiduoke\services\workWechat\WorkWechatAppsService;
use hiduoke\services\workWechat\WorkWechatCustomerService;

class WorkWechatService
{
    // 平台id
    protected $plaid;

    // 应用名称
    protected $addon_name;

    //企业ID
    public $corp_id = "";

    public $err_msg = '';
    private string $auth_type;
    /**
     * @var \EasyWeChat\OpenWork\Application|mixed
     */
    private $openApp;
    /**
     * @var Platform|array|mixed|\think\Model|null
     */
    private $platform;

    use WorkWechatKfService;
    use WorkWechatAppsService;
    use WorkWechatCustomerService;
    use WorkWechatOauth;


    public function __construct($plaid = 0, $addon = '')
    {
        $this->init($plaid, $addon);
    }

    protected function init($plaid = 0, $addon = '')
    {
        if ($plaid != -1) {
            $this->plaid = $plaid ?: get_plaid(false);
            if (!$this->plaid) {
                throw new Exception(lang('The platform does not exist or has been deleted'), 10000);
            }
            $this->platform = (new Platform())->where(['plaid' => $this->plaid])->find();
            if (!$this->platform) {
                throw new Exception("企业微信配置项不存在");
            }
            if (!isset($this->platform ['corp_id'])) {
                throw new Exception("企业ID未填写");
            }
            $this->corp_id = $this->platform['corp_id'];
        }
        if ($addon) {
            $this->addon_name = $addon;
        } else {
            $this->addon_name = input('addon', '');
        }
        $this->getAuthType();
    }

    public function getAuthType()
    {
        //企业微信配置
        $work_wechat_auth_type = (new Config())->getValueByKey("workWechat")['auth_type'] ?? 'manual';
        //用户选择配置
        if ($work_wechat_auth_type == 'manual') {
            $this->auth_type = 'manual';
        } elseif ($work_wechat_auth_type == 'auto') {
            $user_auth_type = $this->platform['auth_type'] ?? 0;//0 手动 1服务商
            if ($user_auth_type == 0) {
                $this->auth_type = 'manual';
            } else {
                $this->auth_type = 'open';
            }
        } else {
            $this->auth_type = 'open';
        }

        return $this->auth_type;
    }
}
